package org.example.myleet.p904;

import java.util.HashMap;
import java.util.Map;

public class Solution {
    public int totalFruit(int[] fruits) {
        Map<Integer, Integer> fruitCount = new HashMap<>(2);
        int l = 0, res = 0;
        for (int i = 0; i < fruits.length; ++i) {
            fruitCount.put(fruits[i], fruitCount.getOrDefault(fruits[i], 0) + 1);
            while (fruitCount.size() > 2) {
                int count = fruitCount.get(fruits[l]);
                --count;
                if (count == 0) {
                    fruitCount.remove(fruits[l]);
                } else {
                    fruitCount.put(fruits[l], count);
                }
                ++l;
            }
            res = Math.max(res, i - l + 1);
        }
        return res;
    }
}
